package com.controller;

import com.alibaba.fastjson.JSON;
import com.proj.Tag;
import com.proj.TagDao;
import com.proj.TagInterface;

import java.util.Arrays;
import java.util.Collection;

import static com.controller.Utility.*;

public class TagController {
    TagInterface tagInterface;

    public String handle(String payload) {
        String op = (String) JSON.parseObject(payload).get("type");
        String response;

        switch (op) {
            case "req_updateTag": {
                response = parsePayloadToClassThen(payload, jTag.class, t -> {
                    tagInterface.updateTag(new TagDao(t.id, t.name, t.details));
                    return "ok";
                });
                break;
            }
            case "req_addTag": {
                response = parsePayloadToClassThen(payload, jTag.class, t -> {
                    Tag tag = tagInterface.createTag(t.name, t.details);
                    jResultCrate<String> r = new jResultCrate<>("resp_addTag", tag.getId());
                    return JSON.toJSONString(r);
                });
                break;
            }
            case "req_deleteTag": {
                response = parsePayloadToStringThenUpdate(payload, tagInterface::deleteTagById);
                break;
            }
            case "req_getTagById": {
                response = parsePayloadToClassThen(payload, String[].class, (String[] ids) -> {
                    Collection<Tag> tags = tagInterface.getTagById(Arrays.asList(ids));
                    return JSON.toJSONString(new jResultCrate<>("resp_getTagById", tags));
                });
                break;
            }
            case "req_getTagByName": {
                response = parsePayloadToStringThenQuery(payload, (String name) -> {
                    Tag tag = tagInterface.getTagByName(name);
                    return new jResultCrate<>("resp_getTagByName", tag);
                });
                break;
            }
            default: {
                response = errBadRequest();
                break;
            }
        }

        return response;
    }

}
